package com.leoman.index.controller;

import com.leoman.admin.entity.AdminRole;
import com.leoman.admin.service.AdminRoleService;
import com.leoman.barrage.entity.Barrage;
import com.leoman.barrage.service.BarrageService;
import com.leoman.comment.entity.Comment;
import com.leoman.comment.service.CommentService;
import com.leoman.common.controller.common.CommonController;
import com.leoman.common.log.entity.Log;
import com.leoman.entity.Configue;
import com.leoman.entity.Constant;
import com.leoman.exception.UserNotFindException;
import com.leoman.feedback.entity.Feedback;
import com.leoman.feedback.service.FeedBackService;
import com.leoman.index.service.LoginService;
import com.leoman.indexapi.service.WorkApiService;
import com.leoman.post.entity.*;
import com.leoman.post.service.*;
import com.leoman.recordcount.entity.RecordCount;
import com.leoman.recordcount.service.RecordCountService;
import com.leoman.report.entity.Report;
import com.leoman.report.service.ReportService;
import com.leoman.role.entity.Modules;
import com.leoman.role.entity.RoleModule;
import com.leoman.role.service.ModulesService;
import com.leoman.role.service.RoleModulesService;
import com.leoman.systemsetting.service.PrizeService;
import com.leoman.user.entity.UserInfo;
import com.leoman.user.service.UserService;
import com.leoman.userapi.service.UserInfoService;
import com.leoman.userapi.service.UserIntegralService;
import com.leoman.utils.CookiesUtils;
import com.leoman.utils.DateUtils;
import com.leoman.utils.ImageUtil;
import com.leoman.utils.Md5Util;
import com.leoman.work.entity.Work;
import com.leoman.work.service.WorkComicService;
import com.leoman.work.service.WorkNovelService;
import com.leoman.work.service.WorkService;
import com.leoman.work.service.WorkVideoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * 基础controller
 * Created by 蔡琦 on 2015/7/29.
 */
@Controller
@RequestMapping(value = "admin")
public class IndexController extends CommonController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private AdminRoleService adminRoleService;

    @Autowired
    private ModulesService modulesService;

    @Autowired
    private RoleModulesService roleModulesService;

    @Autowired
    private UserService userService;

    @Autowired
    private PostBaseService postBaseService;

    @Autowired
    private PostCommentService postCommentService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private FeedBackService feedBackService;

    @Autowired
    private ReportService reportService;

    @Autowired
    private BarrageService barrageService;

    @Autowired
    private WorkService workService;

    @Autowired
    private WorkVideoService workVideoService;

    @Autowired
    private WorkNovelService workNovelService;

    @Autowired
    private WorkComicService workComicService;

    @Autowired
    private RecordCountService recordCountService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserIntegralService userIntegralService;

    @Autowired
    private PrizeService prizeService;

    @Autowired
    private TpPostSubService tpPostSubService;

    @Autowired
    private WorkApiService workApiService;

    @Autowired
    private PostImageService postImageService;

    @Autowired
    private ZbPostInfoService zbPostInfoService;

    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request,
                        String error,
                        ModelMap model) {
        try {
            if (StringUtils.isNotBlank(error)) {
                model.addAttribute("error", error);
            }
            // 先读取cookies，如果存在，则将用户名回写到输入框
            Map<String, Object> params = CookiesUtils.ReadCookieMap(request);
            if (params != null && params.size() != 0) {
                String username = (String) params.get("username");
                model.put("username", username);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "index/login";
    }

    @Log(message = "{0}登录了系统")
    @RequestMapping(value = "/login/check")
    public String checkLogin(String username,
                             String password,
                             HttpServletRequest request,
                             HttpServletResponse response,
                             ModelMap model) {
        response.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();

        // 管理员
        AdminRole adminRole = adminRoleService.sysUserLogin(session, username, Md5Util.md5(password));

        //Boolean success = loginService.login(request, username, Md5Util.md5(password), Constant.MEMBER_TYPE_GLOBLE,remark);

        if (adminRole != null) {
            // 登录成功后，将用户名放入cookies
            int loginMaxAge = 30 * 24 * 60 * 60; // 定义cookies的生命周期，这里是一个月。单位为秒
            CookiesUtils.addCookie(response, "username", username, loginMaxAge);

            // 增加今日访问人数和在线人数
            recordCountService.addCount(1, 1);

            return "redirect:/admin/dashboard";
        }
        model.addAttribute("error", "用户名或密码错误!");
        return "redirect:/admin/login";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request) {
        loginService.logOut(request, Constant.MEMBER_TYPE_GLOBLE);

        // 减少今日在线人数
        recordCountService.addCount(0, -1);
        return "index/login";
    }

    @RequestMapping(value = "/")
    public String index() {
        return "redirect:/admin/dashboard";
    }


    @RequestMapping(value = "/dashboard")
    public String dashboard(HttpServletRequest request,
                            ModelMap model) {

        // 获取当前登录人信息
        Long loginUserId = (Long) request.getSession().getAttribute(Constant.CURRENT_USER_ID);
        AdminRole adminRole = adminRoleService.queryByPK(loginUserId);

        // 根据当前登录人的角色id获取对应的权限列表
        List<Modules> modulesList = modulesService.findFirstList(adminRole.getRole().getId());
        List<RoleModule> roleModuleList = roleModulesService.findListByRoleId(adminRole.getRole().getId());

        for (Modules module : modulesList) {
            for (RoleModule roleModule : roleModuleList) {
                if (module.getId().equals(roleModule.getModule().getParentId())) {
                    module.getModulesList().add(roleModule.getModule());
                }
            }
        }

        // 将该用户信息和权限列表放入界面中
        request.getSession().setAttribute("menu_moduleList", modulesList);
        request.getSession().setAttribute("menu_adminRole", adminRole);

        try {
            // 只有当前角色是超级管理员时，才查询以下数据
            if (adminRole.getRole().getStatus() == 1) {
                // 查询新增会员数量
                List<UserInfo> addUserList = userService.findListNew();
                model.addAttribute("addUserNum", addUserList.size());

                //查询新增用户帖子
                List<PostBase> addUserPostList = postBaseService.findListNew(Constant.POST_TYPE_003);
                model.addAttribute("addUserPostNum", addUserPostList != null ? addUserPostList.size() : 0);

                //查询新增帖子回复
                List<PostComment> postCommentList = postCommentService.findListNew(Constant.COMMENT_TYPE_REPLY);
                model.addAttribute("addPostCommentNum", postCommentList != null ? postCommentList.size() : 0);

                //查询新增视频评论
                List<Comment> videoCommentList = commentService.findListNew(Constant.WORKCOMMENT_TYPE_000);
                model.addAttribute("addVideoCommentNum", videoCommentList != null ? videoCommentList.size() : 0);

                //查询新增小说评论
                List<Comment> novelCommentList = commentService.findListNew(Constant.WORKCOMMENT_TYPE_001);
                model.addAttribute("addNovelCommentNum", novelCommentList != null ? novelCommentList.size() : 0);

                //查询新增漫画评论
                List<Comment> comicCommentList = commentService.findListNew(Constant.WORKCOMMENT_TYPE_002);
                model.addAttribute("addComicCommentNum", comicCommentList != null ? comicCommentList.size() : 0);

                //查询新增意见反馈
                List<Feedback> feedbackList = feedBackService.findListNew();
                model.addAttribute("addFeedBackNum", feedbackList != null ? feedbackList.size() : 0);

                //查询新增举报
                List<Report> reportList = reportService.findListNew();
                model.addAttribute("addReportNum", reportList != null ? reportList.size() : 0);

                //查询新增视频弹幕
                List<Barrage> videoBarrageList = barrageService.findListNew(Constant.BARRAGE_TYPE_000);
                model.addAttribute("addVideoBarrageNum", videoBarrageList != null ? videoBarrageList.size() : 0);

                //查询新增漫画弹幕
                List<Barrage> comicBarrageList = barrageService.findListNew(Constant.BARRAGE_TYPE_001);
                model.addAttribute("addComicBarrageNum", comicBarrageList != null ? comicBarrageList.size() : 0);

                //查询用户帖子总数
                List<PostBase> userPostList = postBaseService.findByType(Constant.POST_TYPE_003);
                model.addAttribute("userPostNum", userPostList != null ? userPostList.size() : 0);

                //查询官方帖子总数
                List<PostBase> postList = postBaseService.findByDeleteStatus();
                model.addAttribute("postNum", postList != null && userPostList != null ? (postList.size() - userPostList.size()) : 0);

                //查询加精帖子
                List<PostBase> essencePostList = postBaseService.findByEssence(1);
                model.addAttribute("essencePostNum", essencePostList != null ? essencePostList.size() : 0);

                //查询投票贴
                List<PostBase> tpPostList = postBaseService.findByType(Constant.POST_TYPE_002);
                model.addAttribute("tpPostNum", tpPostList != null ? tpPostList.size() : 0);

                //查询直播贴
                List<PostBase> zbPostList = postBaseService.findByType(Constant.PLAY_TYPE_001);
                model.addAttribute("zbPostNum", zbPostList != null ? zbPostList.size() : 0);

                //查询已锁帖
                List<PostBase> lockPostList = postBaseService.findByStatus(Constant.POST_STATUS_002);
                model.addAttribute("lockPostNum", lockPostList != null ? lockPostList.size() : 0);


                //查询视频总集数
                List<Work> videoList = workService.findByType(Constant.CATEGORY_TYPE_004);
                Integer videoSum = 0;
                for (Work work : videoList) {
                    videoSum += workVideoService.findByWorkId(work.getId()).size();
                }
                model.addAttribute("videoSum", videoSum);

                //查询漫画总部数
                List<Work> comicList = workService.findByType(Constant.CATEGORY_TYPE_006);
                Integer comicSum = 0;
                for (Work work : comicList) {
                    comicSum += workComicService.findByWorkId(work.getId()).size();
                }
                model.addAttribute("comicSum", comicSum);

                //查询小说总部数
                List<Work> novelList = workService.findByType(Constant.CATEGORY_TYPE_005);
                Integer novelSum = 0;
                for (Work work : novelList) {
                    novelSum += workNovelService.findByWorkId(work.getId()).size();
                }
                model.addAttribute("novelSum", novelSum);

                //查询弹幕总数
                List<Barrage> barrageList = barrageService.queryAll();
                model.addAttribute("barrageSum", barrageList != null ? barrageList.size() : 0);

                //查询全部主创会员
                List<UserInfo> creatorList = userService.findByStatus();
                model.addAttribute("creatorSum", creatorList != null ? creatorList.size() : 0);

                //查询普通会员
                List<UserInfo> userInfoList = userService.queryAll();
                model.addAttribute("userInfoSum", userInfoList.size() - creatorList.size());

                // 查询今日访问人数和在线人数

                // 查询今日访问人数和在线人数
                RecordCount recordCount = recordCountService.queryByPK(1L);
                model.addAttribute("visitCount", recordCount.getVisitCount());
                model.addAttribute("onlineCount", recordCount.getOnlineCount());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "index/index";
    }

    @RequestMapping(value = "/myLevel")
    public String myLevel(ModelMap model,
                          Long userId) {
        try {
            if (null != userId) {
                UserInfo userInfo = userInfoService.findOne(userId);

                model.addAttribute("userInfo", userInfo);

                // 计算升级所需经验值
                model.addAttribute("levelUpIntegral", userIntegralService.getMoreIntegral(userInfo.getIntegral()));
            }
        } catch (UserNotFindException e) {
            e.printStackTrace();
        }

        return "prize/mylevel";
    }

    @RequestMapping(value = "/rules")
    public String rules() {
        return "prize/rules";
    }

    @RequestMapping(value = "/prize")
    public String prize(ModelMap model,
                        Long userId) {
        try {
            if (null != userId) {
                UserInfo userInfo = userInfoService.findOne(userId);

                model.addAttribute("userInfo", userInfo);

                model.addAttribute("prizeList", prizeService.findList());
            }
        } catch (UserNotFindException e) {
            e.printStackTrace();
        }

        return "prize/prize";
    }

    @RequestMapping(value = "/addPrize")
    public void addPrize(Long userId,
                         Integer coin) {
        try {
            UserInfo userInfo = userInfoService.findOne(userId);
            userIntegralService.changeCoin(userInfo, "抽奖消耗10个馒头", Constant.DEFAULT_COIN * -1);
            if (null != coin && coin > 0) {
                userIntegralService.changeCoin(userInfo, "中奖获取" + coin + "个馒头", coin);
            }
        } catch (UserNotFindException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/toShareInfo")
    public String toShareInfo(Long sourceId, Integer type, ModelMap model) {
        String path = "";

        try {
            // 1=帖子 2=作品
            if (type == 1) {
                PostBase postBase = postBaseService.findOneById(sourceId);

                postBase.getUserInfo().setAvater(ImageUtil.clearUploadUrl(postBase.getUserInfo().getAvater()));
                if (StringUtils.isNotBlank(postBase.getContent())) {
                    postBase.setContent(postBase.getContent().replaceAll("&lt", "<").replaceAll("&gt", ">"));
                }
                model.addAttribute("postBase", postBase);

                // 帖子类型 0:普通帖 1:直播帖 2:投票帖 3:用户帖
                switch (postBase.getType()) {
                    case 2:
                        List<TpPostSub> list = tpPostSubService.findByPostId(sourceId);
                        for (TpPostSub tpPostSub : list) {
                            tpPostSub.setCover(ImageUtil.clearUploadUrl(tpPostSub.getCover()));
                        }
                        model.addAttribute("tpPostSubList", list);
                        if (postBase.getCreateDate() <= System.currentTimeMillis()) {
                            model.addAttribute("hiddenTime", "");
                        } else {
                            model.addAttribute("hiddenTime", com.leoman.utils.DateUtils.longToString(postBase.getCreateDate(), "yyyy-MM-dd hh:mm:ss"));
                        }
                        path = "index/tpPostInfo";
                        break;
                    case 0:
                    case 3:
                        if (postBase.getType().equals(Constant.POST_TYPE_003)) {
                            List<PostImage> postImages = postImageService.findList(sourceId, Constant.POST_TYPE_003);
                            if (null != postImages && postImages.size() > 0) {
                                postBase.setSuolue(ImageUtil.clearUploadUrl(postImages.get(0).getUrl()));
                            }
                        }
                        model.addAttribute("createTime", DateUtils.getDateToString(postBase.getCreateDate()) + DateUtils.longToString(postBase.getCreateDate(), "hh:mm"));
                        path = "index/ptPostInfo";
                        break;
                    case 1:
                        List<ZbPostInfo> zbPostInfoList = zbPostInfoService.findByPostId(postBase.getId());
                        for (ZbPostInfo zbPostInfo : zbPostInfoList) {
                            zbPostInfo.setImageList(postImageService.findList(zbPostInfo.getId(), Constant.POST_TYPE_001));
                            zbPostInfo.setShowTime(DateUtils.longToString(zbPostInfo.getCreateDate(), "MM-dd hh:mm"));
                        }
                        model.addAttribute("createTime", DateUtils.getDateToString(postBase.getCreateDate()) + DateUtils.longToString(postBase.getCreateDate(), "hh:mm"));
                        model.addAttribute("zbPostInfoList", zbPostInfoList);
                        model.addAttribute("imageTitle", Configue.getUploadUrls());
                        path = "index/zbPostInfo";
                        break;
                }
            } else {
                Work work = workService.findOneById(sourceId);

                // 类别 4:视频 5：小说 6：漫画
                switch (work.getCategory().getType()) {
                    case 4:
                        model.addAttribute("workVideo", workApiService.findVideo(sourceId, null));
                        path = "index/videoInfo";
                        break;
                    case 5:
                        model.addAttribute("workNovel", workApiService.findNovel(sourceId, null));
                        path = "index/novelInfo";
                        break;
                    case 6:
                        model.addAttribute("workComic", workApiService.findComic(sourceId, null));
                        path = "index/comicInfo";
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return path;
    }

    @RequestMapping(value = "/playVideo")
    public String playVideo(ModelMap model, Long bid) {
        model.addAttribute("bid", bid);
        return "index/playVideo";
    }
}
